;(function(){
	var dutyId = $("#approveBatchForm input[name=approveDuty]").val();
    //日期
    $("#queryDate").daterangepicker({
		locale : {
			format: 'YYYY-MM-DD',
			separator:' 到 ',
			applyLabel : '确定',
			cancelLabel : '取消',
			customRangeLabel : '自定义',
			daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
			monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月',
				'七月', '八月', '九月', '十月', '十一月', '十二月' ],
			firstDay : 1
		},
		ranges: {
			'今天': [moment().startOf('day'), moment()],
			'昨天': [moment().subtract(1,'days').startOf('day'), moment().subtract(1,'days').endOf('day')],
			'本周': [moment().startOf("week").add(1,'days'),moment().endOf("week").add(1,'days')],
			'上周': [moment().subtract(1,'weeks').startOf("week").add(1,'days'),moment().subtract(1,'weeks').endOf("week").endOf("week").add(1,'days')],
			'本月': [moment().startOf("month"),moment().endOf("month")],
			'上个月': [moment().subtract(1,"month").startOf("month"),moment().subtract(1,"month").endOf("month")],
			'最近7天': [moment().subtract(6,'days'), moment()],
			'最近30天': [moment().subtract(29,'days'), moment()]
		},
		applyClass:'btn-primary',
		alwaysShowCalendars: true,
		autoclose:true
    });
    
	//加载表单
	  DataTable = function(){
	 	return {
	 		init: function () {
	 			var dutyTable = $('#approveInit').dataTable({
	 				"bPaginate": true,  //是否显示分页
//	             	"iDisplayLength": 10,
	             	"bLengthChange": true,//每页显示的记录数
	             	"bFilter": false, //搜索栏
	             	"bSort": true, //是否支持排序功能
	             	"bInfo": true, //显示表格信息
	             	"bAutoWidth": false,  //自适应宽度
	             	"bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
	             	//"sPaginationType": "", //分页，一共两种样式，full_numbers和two_button(默认)
	             	"sAjaxSource" : ctx+'/apply/selectAllByWhere',
	         		"fnServerData": retrieveData,//用于替换默认发到服务端的请求操作  
	             	"bServerSide": true,
	             	"bDestroy": true,
	                 "bRetrieve": false,
	                 "oLanguage" : {
	                 	"sLengthMenu" : "每页显示 _MENU_ 条记录",
	         			"sZeroRecords" : "抱歉， 没有找到",
	         			"sInfo" : "从 _START_ 到 _END_ / 共 _TOTAL_ 条数据",
	         			"sInfoEmpty" : "找不到相关数据",
	         			"sInfoFiltered" : "数据表中共为 _MAX_ 条记录)",
	         			"sProcessing": "正在加载中...",
	         			"sSearch": "搜索",
	         			"oPaginate" : {
	         				"sFirst" : "首页",
	         				"sPrevious" : "前一页",
	         				"sNext" : "后一页",
	         				"sLast" : "尾页"
	         			},
	                 },
	                 "aoColumns" : [
	                        {
	                        "mData": "applyId", 'sClass': "text-center", "bSortable": false, "mRender": function (data, type, full) {
	                        return '<label  class="labletab" style="padding-top: 0px"> <input name="ajaxcheckbox" type="checkbox" class="checkchild" > <span class="text" applyId=""></span> </label>';
	                        }
	                        },
	                        {"mData": "applicantDate", 'sClass': "text-center"},
	 						{"mData": "departmentName", 'sClass': "text-center"},
	 						{"mData": "applicantName", 'sClass': "text-center"},
	 						{"mData": "pCostClassName", 'sClass': "text-center"},
	 						{"mData": "costClassName", 'sClass': "text-center"},
	 						{"mData": "expendDetail", 'sClass': "text-center"},
	 						{"mData": "money", 'sClass': "text-center"},
	 						{"mData": "paymentFrom", 'sClass': "text-center"},
	 						{
	 			                "mData": "applyId",
	 			                'sClass': "text-center",
	 			                "bSortable": false,
	 			                "mRender": function (data, type, full ) {
	 			                	var u = "<a data-record='"+JSON.stringify(full)+"' class='btn btn-warning btn-xs'   data-toggle='modal' data-backdrop='static'  ><i class='fa fa-folder-open-o' ></i> 查看</a>&nbsp&nbsp";
	 			                    var e = "<a data-record='"+JSON.stringify(full)+"' class='btn btn-info btn-xs edit' data-toggle='modal' data-backdrop='static' data-target='#approveModel' ><i class='fa fa-edit'></i>审批</a>&nbsp&nbsp";
	 			                    return u+e;
	 			                }
	 			            }

	                 ],
	                 "aoColumnDefs": [{
	 	   	            sDefaultContent: '',
	 	   	            aTargets: ['_all']
	 	   	        }],
	 	   	    "fnRowCallback":function(nRow,aData,iDisplayIndex){
	 	   	    	$('td:eq(0) span',nRow).attr("applyId",aData.applyId);
	 	   	    	$('td:eq(8)',nRow).html(aData.paymentFrom=='1'?'集团支付':'分校支付');
	 	   	    	return nRow;
	 	   	     }
	 			});
	 			//每页显示记录数
	 			$('.dataTables_info').parent().append($('.dataTables_length'));
	 		}
	 	}
	 }();
	 DataTable.init();
	 
	 $('.checkAll').on('click',function(){
		 if($(this).is(":checked")){
			 $('.checkchild').prop('checked',true);
		 }else{
			 $('.checkchild').prop('checked',false);
		 }
	 });
	 //一键审批model
	 $('#approveBatchButton').on('click',function(){
		 if($('#approveInit input.checkchild:checked').length==0){
			 toastr.error("请选择审批的条目");
			 return false;
		 }
		 var totalmoney = 0;
		 $('#approveInit input.checkchild:checked').each(function(i,item){
			 totalmoney+= parseFloat($(item).parent().parent().parent().find('td').eq(7).text());
		 });
		 $('#approveBatchForm input[name=approveDate]').val(getFormatDate(new Date()));
		 $('#approveBatchForm input[name=approveCostTotal]').val(totalmoney);
		 $('#approveBatchModel').show();
	 });
	 
	 // 查看 编辑
	 $('#approveInit').on('click','a.btn-xs',function(){
		 var data = $(this).attr('data-record');
		 data = JSON.parse(data);
		 if($(this).hasClass('btn-warning')){
			 loadHtml('/handleCheck/index?isAccraditation=1&applyId='+data.applyId);
		 }else if($(this).hasClass('btn-info')){
			 approveInfo(true,data);
		 }
	 });
	 //
	 function approveInfo(flag,data){
		 $('#approveForm input[name=applyId]').val(data.applyId);
		 !flag?$('#approveButton').css('display','none'):$('#approveButton').css('display','block');
		 $('#approveForm textarea[name=approveAdvice]').prop('disabled',!flag);
		 $('#approveForm input[name=approveDate]').val(getFormatDate(new Date()));
		 addApproveFlow(data);
		 $('#approveModel').show();
		 
	 }
	 function addApproveFlow(result){
		 var applyId = result.applyId;
		 $('#approveFlow').html('');
		 console.log(ctx + "/accraditation/getApproveFlow/"+applyId);
		 var html='<ul class="timeline">';
		 html+='<li class="timeline-node"><a class="btn btn-palegreen">当前</a></li>'
		 $.ajax({
				url: ctx + "/accraditation/getApproveFlow/"+applyId,
				dataType: 'json',
				async:true,
				success: function(data){
					var toggle = true;
					var length = data.length;
					 html+='<li>';
					 html+='<div class="timeline-datetime">';
					 html+='</div>';
					 html+='<div class="timeline-badge sky pass-ing">';   
			         html+='<i class="handle-num pass-content">'+(length+2)+'</i>';
			         html+='</div>';
			         html+='<div class="timeline-panel">';
			         html+='<div class="timeline-header bordered-bottom bordered-blue">';
			         html+='<p class="timeline-datetime">';
			         html+='<small class="text-muted">';
			         html+='<i class="glyphicon glyphicon-time"></i>';
			         html+='</small>';
			         html+='</p>';
			         html+='</div>';
			         html+=' <div class="timeline-body">';
			         html+='<a href="#"></a> <a href="#">审批人:'+($('#approveForm input[name=approveUserName]').val()+('<br/><br/>审批状态:待审批'))+'</a>';
			         html+='<div class="tl-wide text-center" style="padding: 5px; margin-top:10px; margin-bottom: 10px;"></div>';
			         html+='<i class="text-muted text-sm"></i>';
			         html+='</div>';	
			         html+='</div>';
			         html+='</li>';
			         length = length+1;
					$(data).each(function(i,item){
						if(toggle){
							html+='<li class="timeline-inverted">';
							toggle=false;
						}else{
							html+='<li class="">';
							toggle=true;
						}
						
						html+='<div class="timeline-datetime">';
						html+='<span class="timeline-time">'+(item.createDate.split(' ')[1])+'</span>';
						html+='<span class="timeline-date">'+(item.createDate.split(' ')[0])+'</span>';
						html+='</div>';//审批不通过
						if(item.approveStatus=='0'){
							html+='<div class="timeline-badge unpass">';
						}else{
							html+='<div class="timeline-badge pass">';
						}
						   
                        html+='<i class="handle-num pass-content">'+(length--)+'</i>';
                        html+='</div>';
                        html+='<div class="timeline-panel">';
                        html+='<div class="timeline-header bordered-bottom bordered-blue">';
                        html+='<p class="timeline-datetime">';
                        html+='<small class="text-muted">';
                        html+='<i class="glyphicon glyphicon-time"></i>';
                        html+='<span class="timeline-date">'+(item.createDate.split(' ')[1])+'</span>';
                        html+='<span class="timeline-time">'+(item.createDate.split(' ')[0])+'</span>';
                        html+='</small>';
                        html+='</p>';
                        html+='</div>';
                        html+=' <div class="timeline-body">';
                        html+='<a href="#"></a> <a href="#">审批人:'+(item.approveUserName+'<br/><br/>审批状态:'+(item.approveStatus=='0'?'未通过':'已通过'))+'</a>';
                        html+='<div class="tl-wide text-center" style="padding: 5px; margin-top:0px; margin-bottom: 10px;"></div>';
                        var approveHtml = "";
                        var splitlength = Math.ceil(item.approveAdvice.length/8);
                        var locationInit = 4;
                        for(var i=0;i<splitlength;i++){
                        	if(i==0){
                        		approveHtml+=item.approveAdvice.substring(0,locationInit);
                        	}else{
                        		approveHtml+='<br/>'+item.approveAdvice.substring(locationInit,locationInit+8);
                        		locationInit=locationInit+8;
                        	}
                        }
                        html+='<p class="text-muted text-sm">'+('审批意见:')+approveHtml+'</p>';
                        html+='</div>';	
                        html+='</div>';
                        html+='</li>';
					});
					 if(toggle){
						 html+='<li class="timeline-inverted">';
					 }else{
						 html+='<li>';
					 }
					 html+='<div class="timeline-datetime">';
					 html+='<span class="timeline-time">'+(result.createDate.split(' ')[1])+'</span>';
					 html+='<span class="timeline-date">'+(result.createDate.split(' ')[0])+'</span>';
					 html+='</div>';
					 html+='<div class="timeline-badge sky pass-ing">';   
			         html+='<i class="handle-num pass-content">1</i>';
			         html+='</div>';
			         html+='<div class="timeline-panel">';
			         html+='<div class="timeline-header bordered-bottom bordered-blue">';
			         html+='<p class="timeline-datetime">';
			         html+='<small class="text-muted">';
			         html+='<i class="glyphicon glyphicon-time"></i>';
                     html+='<span class="timeline-date">'+(result.createDate.split(' ')[1])+'</span>';
                     html+='<span class="timeline-time">'+(result.createDate.split(' ')[0])+'</span>';
			         html+='</small>';
			         html+='</p>';
			         html+='</div>';
			         html+=' <div class="timeline-body">';
			         html+='<a href="#"></a> <a href="#">申请人:'+(result.applicantName+('<br/><br/>申请状态:提出申请'))+'</a>';
			         html+='<div class="tl-wide text-center" style="padding: 5px; margin-top:10px; margin-bottom: 10px;"></div>';
			         html+='<i class="text-muted text-sm"></i>';
			         html+='</div>';	
			         html+='</div>';
			         html+='</li>'
	 				 html+="</ul>";
	 				$('#approveFlow').html(html);
				}
		 				
			});
		
	 }
	 //审批
	    $('#approveForm').bootstrapValidator({
	        message: 'This value is not valid',
	        feedbackIcons: {
	            valid: 'glyphicon glyphicon-ok',
	            invalid: 'glyphicon glyphicon-remove',
	            validating: 'glyphicon glyphicon-refresh'
	        },
	        fields: {//表单验证
	        	approveUserName: {
	                validators: {
	                    notEmpty: {
	                        message: '审批人不能为空'
	                    }
	                }
	            },
	            approveAdvice: {
	                validators: {
	                    notEmpty: {
	                        message: '审批意见不能为空'
	                    }
	                }
	            }
	           
	        },
	        submitHandler: function (validator, form, submitButton) {
	        	if($(submitButton).attr('id')=='approvePass'){
	        		$('#approveForm input[name=approveStatus]').val('1');
	        	}else{
	        		$('#approveForm input[name=approveStatus]').val('0');
	        	}
				 $.ajax({
						type: "POST",
						url: ctx + "/accraditation/addNewRecord",
						data: $("#approveForm").serialize(),
						dataType: 'json',
						success: function(msg){
							if(msg.status == 'success'){
								$('#approveModel').modal('hide');
								toastr.success(msg.msg);
								DataTable.init();
							}else{
								$('#approveModel').modal('hide');
								DataTable.init();
								toastr.error(msg.msg);
							}

						}
					});
	            return true;
	        }
	    });
		 //一键审批
	    $('#approveBatchForm').bootstrapValidator({
	        message: 'This value is not valid',
	        feedbackIcons: {
	            valid: 'glyphicon glyphicon-ok',
	            invalid: 'glyphicon glyphicon-remove',
	            validating: 'glyphicon glyphicon-refresh'
	        },
	        fields: {//表单验证
	        	approveUserName: {
	                validators: {
	                    notEmpty: {
	                        message: '审批人不能为空'
	                    }
	                }
	            },
	            approveAdvice: {
	                validators: {
	                    notEmpty: {
	                        message: '审批意见不能为空'
	                    }
	                }
	            }
	           
	        },
	        submitHandler: function (validator, form, submitButton) {
	        	if($(submitButton).attr('id')=='approveBatchPass'){
	        		$('#approveBatchForm input[name=approveStatus]').val('1');
	        	}else{
	        		$('#approveBatchForm input[name=approveStatus]').val('0');
	        	}
	        	var applyId="";
	        	 $('#approveInit input.checkchild:checked').each(function(i,item){
	        		 applyId+=$(item).next().attr('applyId')+",";
	        	 });
	        	 applyId  =applyId.substring(0,applyId.lastIndexOf(","));
	        	 $('#approveBatchForm input[name=applyId]').val(applyId);
				 $.ajax({
						type: "POST",
						url: ctx + "/accraditation/addNewRecord",
						data: $("#approveBatchForm").serialize(),
						dataType: 'json',
						success: function(msg){
							if(msg.status == 'success'){
								$('#approveBatchModel').modal('hide');
								toastr.success(msg.msg);
								DataTable.init();
							}else{
								$('#approveBatchModel').modal('hide');
								toastr.error(msg.msg);
								DataTable.init();
								
							}

						}
					});
	            return false;
	        }
	    });
	    
	 /**
	  * 回调函数
	  * @param sSource
	  * @param aoData
	  * @param fnCallback
	  * @returns
	  */
	 function retrieveData( sSource, aoData, fnCallback, oSettings ) {
	 	var beganAndEnd = $("#queryDate").val();
	 	if(beganAndEnd && beganAndEnd.length != 0){
	     	 var minDate = $("#queryDate").val().split("到")[0] ;
	         var maxDate = $("#queryDate").val().split("到")[1] ;
	         aoData.push({ "name": "beginTime", "value": minDate.trim() });
	         aoData.push({ "name": "endTime", "value": maxDate.trim() });
	     }
	     aoData.push( { "name": "pageNum", "value": (Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength )+1) });
	     aoData.push( { "name": "pageSize", "value": oSettings._iDisplayLength }); 
	     aoData.push( { "name": "approveNextDuty", "value": dutyId });
	     var searchVal = $('#searchVal').val();
	     if(searchVal && searchVal.length != 0){
	     	aoData.push({ "name": "searchVal", "value": searchVal.trim() });
	     }
	     $.ajax( {  
	         "url": sSource,  
	         "data": aoData,  
	         "cache": false,  
	         "dataType": 'json', 
	         "type": "POST", 
	         "success" :function(response) {
	         	fnCallback(response.returnObject);
	         	initTotalIncome();
	         }  
	     } );  
	 }
	 
	 //统计
	 function initTotalIncome(){
			var beginTime = $("#queryDate").val().split("到")[0];
			var endTime = $("#queryDate").val().split("到")[1];
			var searchVal = $("#searchVal").val();
			$.ajax({
		        url: ctx + '/apply/getTotalMoneyByWhere',
		        data:{"beginTime":beginTime?beginTime.trim():null,"endTime":endTime?endTime.trim():null,"searchVal":searchVal?searchVal.trim():null,"approveNextDuty":dutyId},
		        type: 'POST',
		        dataType: 'json',
		        success: function (data) {
		        		var html = '<tr class="odd">';
		        		for(var i=0;i<6;i++) html+='<td class="text-center"></td>';
		        		 html+=
		        		'<td class="text-center red">统计:</td>'+
		        		'<td class="text-center">'+data.data+'</td>'+
		        		'<td class="text-center"></td>'+
		        		'<td class="text-center"></td>'+
		        		'</tr>';
		        		$("#approveInit").find("tbody").prepend(html);
		        }
			});
		}
    //富文本编辑器
   /* var editor;
    KindEditor.ready(function (K) {
        editor = K.create('textarea.content', {
            allowFileManager: true
        })
    });*/

    //导航
    $(".nav_par").on("click","a",function () {
        $(this).addClass("nav-active").parent().siblings().find("a").removeClass("nav-active");
        //console.log($(this).addClass("nav-active").parent().sibling())
    })

    //日期
	    $('.date-picker').datepicker({
		language : 'zh-CN',
		format : 'yyyy-mm-dd'
	}).on('changeDate', function() {
		$(this).datepicker('hide');
	});
	//日期格式化
	Date.prototype.format = function(format) {
	var o = {
		"M+" : this.getMonth() + 1,
		"d+" : this.getDate(),
		"h+" : this.getHours(),
		"m+" : this.getMinutes(),
		"s+" : this.getSeconds(),
		"q+" : Math.floor((this.getMonth() + 3) / 3),
		"S" : this.getMilliseconds()
	}
	if (/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	}
	for ( var k in o) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
					: ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
	return format;
}  

	 function getFormatDate(date, pattern) {
		if (date == undefined) {
			date = new Date();
		}
		if (pattern == undefined) {
			pattern = "yyyy-MM-dd hh:mm:ss";
		}
		return date.format(pattern);
}  
	
	function getFormatDateByLong(l, pattern) {
		return getFormatDate(new Date(l), pattern);  
   }
    
   })(jQuery)
   function tiaozhuan(){
	loadHtml('/accraditationCheck/index');
	}


//回车搜索
function search(){
	if(event.keyCode==13){
		DataTable.init();
	}
}